#!/usr/bin/env python

import argparse
import errno
import glob
import os
import platform
import subprocess
import sys


SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
BOTO_DIR = os.path.join(SOURCE_ROOT, 'vendor', 'boto')

PLATFORM_KEY = {
  'cygwin': 'win',
  'darwin': 'osx',
  'linux2': 'linux',
  'win32': 'win',
}[sys.platform]


def main():
  args = parse_args()

  try:
    upload(args.target_arch)
  except AssertionError as e:
    return e.message


def parse_args():
  parser = argparse.ArgumentParser(description='Upload distribution')
  parser.add_argument('-t', '--target_arch', default='x64', help='x64 or ia32')
  return parser.parse_args()


def upload(target_arch):
  os.chdir(SOURCE_ROOT)
  bucket, access_key, secret_key = s3_config()
  commit = command_output(['git', 'rev-parse', 'HEAD']).strip()

  if os.environ.has_key('MAS_BUILD'):
    platform = 'mas'
  else:
    platform = PLATFORM_KEY

  s3put(bucket, access_key, secret_key, SOURCE_ROOT,
        'libchromiumcontent/{0}/{1}/{2}'.format(platform, target_arch, commit),
        glob.glob('libchromiumcontent*.zip'))


def s3_config():
  config = (os.environ.get('LIBCHROMIUMCONTENT_S3_BUCKET', ''),
            os.environ.get('LIBCHROMIUMCONTENT_S3_ACCESS_KEY', ''),
            os.environ.get('LIBCHROMIUMCONTENT_S3_SECRET_KEY', ''))
  message = ('Error: Please set the $LIBCHROMIUMCONTENT_S3_BUCKET, '
             '$LIBCHROMIUMCONTENT_S3_ACCESS_KEY, and '
             '$LIBCHROMIUMCONTENT_S3_SECRET_KEY environment variables')
  assert all(len(c) for c in config), message
  return config


def boto_path_dirs():
  return [
    os.path.join(BOTO_DIR, 'build', 'lib'),
    os.path.join(BOTO_DIR, 'build', 'lib.linux-x86_64-2.7')
  ]


def run_boto_script(access_key, secret_key, script_name, *args):
  env = os.environ.copy()
  env['AWS_ACCESS_KEY_ID'] = access_key
  env['AWS_SECRET_ACCESS_KEY'] = secret_key
  env['PYTHONPATH'] = os.path.pathsep.join(
      [env.get('PYTHONPATH', '')] + boto_path_dirs())

  boto = os.path.join(BOTO_DIR, 'bin', script_name)
  subprocess.call([sys.executable, boto] + list(args), env=env)


def s3put(bucket, access_key, secret_key, prefix, key_prefix, files):
  args = [
    '--bucket', bucket,
    '--prefix', prefix,
    '--key_prefix', key_prefix,
    '--grant', 'public-read'
  ] + files

  run_boto_script(access_key, secret_key, 's3put', *args)


def command_output(args):
  process = subprocess.Popen(args, stdout=subprocess.PIPE)
  output = process.communicate()[0]
  if process.returncode != 0:
    raise subprocess.CalledProcessError(process.returncode, args)
  return output


if __name__ == '__main__':
  sys.exit(main())
